from django.db import connection
from django.http import HttpResponse

from user.models import User


# Create your views here.
def hello_world(request):
    return HttpResponse("Hello, World!")


def get_all_user(request):
    # 获取数据连接
    cursor = connection.cursor()
    # 执行sql语句
    cursor.execute("select * from user")
    # 获取所有数据
    rows = cursor.fetchall()
    # 遍历数据
    for row in rows:
        print(row)
    return HttpResponse("查找成功")


def add_user(request):
    user = User(name="王五", age=18, sex=1, address="湖北省武汉市江夏区", phone="13488886666")
    user.save()
    return HttpResponse("新增成功")


def delete_user(request):
    user = User.objects.get(id=1)
    user.delete()
    return HttpResponse("删除成功")


def update_user(request):
    try:
        user = User.objects.get(name="李四")
        user.age = 24
        user.save()
    except User.DoesNotExist:
        print("用户不存在")
    return HttpResponse("修改成功")


def select_user(request):
    user_list = User.objects.all()
    # 排序
    # user_list = User.objects.all().order_by("name")
    # 按条件查找
    # user_list = User.objects.all().filter(name="王五")
    for user in user_list:
        print(user)
    return HttpResponse("查找成功")
